<template>
  <div class="flex flex-col items-center  w-50%">
    <h2 class="font-size-36px fw-500 lh-24px mb-48px">欢迎登录!</h2>
    <div class="p-20px w-full box-border bg-#fff">
      <el-form
        ref="loginForm"
        class="login-form"
        :model="formData"
        :rules="rules"
        :show-message="false"
        label-position="top"
      >
        <el-form-item label="手机号" prop="username">
          <el-input v-model="formData.username" placeholder="请输入" :maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <PwdInput v-model="formData.password" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </div>
    <div class="w-full mt-28px mb-30px flex justify-between font-size-16px">
      <span class="link cursor-pointer" @click="changeType('register')"
        >注册</span
      >
      <span class="link cursor-pointer" @click="changeType('find')"
        >忘记密码？</span
      >
    </div>
    <el-button
      type="primary"
      :loading="loading"
      class="w-full h-60px font-size-20px"
      @click="doLogin"
      >登录</el-button
    >
  </div>
</template>

<script setup>
import { PwdInput } from "@/components";
import { useLoading } from "@/hooks";
import { setToken } from "@/utils/auth";
const loginForm = ref();
const formData = ref({
  username: "",
  password: "",
});
const { loading, setLoading } = useLoading();
const rules = reactive({
  username: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const $api = inject("$api");
const route = useRoute();
const router = useRouter();

const handleFullPath = (fullPath) => {
  const [path, queryStr] = fullPath.split("?");
  let query = null;
  if (queryStr) {
    const queryArr = queryStr.split("&");
    query = Object.fromEntries(queryArr.map((i) => i.split("=")));
  }
  return {
    path,
    query,
  };
};

const doLogin = () => {
  loginForm.value.validate(async (valid) => {
    if (valid) {
      setLoading(true);
      try {
        const { token } = await $api.system.login(formData.value);
        if (token) {
          ElMessage.success("登录成功");
          setToken(token);
          const { path, query } = handleFullPath(route.query.redirect);
          router.push({
            path,
            query,
            replace: true,
          });
        }
      } finally {
        setLoading(false);
      }
    }
  });
};

const changeType = inject("changeType");
</script>
